package com.hex.ds.hdrs.common.utils;


import com.hex.ds.hdrs.common.constant.ErrorCode;
import com.hex.ds.hdrs.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Package: com.hex.dataService.hdrs.scheduleService.other.utils
 * @ClassName MultipartFileUtil
 * @Description:MultipartFile工具类
 * @Author: <gc.zuo>
 * @Date 2021/6/8 20:07
 * @Version v1.0
 **/
@Slf4j
public class MultipartFileUtil {

    /**
     * @Method: multipartFileToFile <br>
     * @Param: [file] <br>
     * @Return: java.io.File <br>
     * @Description：<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/6/8 20:07 <br>
     * @Version： V1.0<br>
     */
    public static File multipartFileToFile(MultipartFile file){
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            try{
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            }catch (IOException ie){
                log.error("【multipartFileToFile】IO异常:{}", ie.getMessage(), ie);
                throw new BizException(ErrorCode.ERROR_600005);
            }
        }
        return toFile;
    }

    /**
     * @Method: inputStreamToFile <br>
     * @Param: [ins, file] <br>
     * @Return: void <br>
     * @Description：获取流文件<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/6/8 20:08 <br>
     * @Version： V1.0<br>
     */
    private static void inputStreamToFile(InputStream ins, File file) throws IOException {
        try (OutputStream os = new FileOutputStream(file)) {
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ins != null) {
                ins.close();
            }
        }
    }

    /**
     * @Method: delteTempFile <br>
     * @Param: [file] <br>
     * @Return: void <br>
     * @Description：删除本地临时文件<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/6/8 20:08 <br>
     * @Version： V1.0<br>
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }
}
